<?php

namespace app\admin\controller;

use app\model\CityModel;
use support\Request;
use support\Response;
use Exception;
use app\model\Util;

class CityController
{
    /**
     * 获取城市列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            
            $query = CityModel::query()
                ->whereNull('deleted_at')
                ->orderBy('id', 'desc');
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = $item->created_at ?: 0;
                $item['updated_at'] = $item->updated_at ?: 0;

                $item['image_url'] = Util::pathToUrl($item->image);
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取城市详情
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        try {
            $id = $request->get('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $city = CityModel::where('id', $id)
                ->where('deleted_at', 0)
                ->first();
                
            if (!$city) {
                throw new Exception('城市不存在');
            }

            return json([
                'data' => $city,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 提交/创建城市
     * @param Request $request
     * @return Response
     */
    public function submit(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['name']) || empty($data['code'])) {
                throw new Exception('城市名称和代码不能为空');
            }

            // 检查城市代码是否重复
            $existingCity = CityModel::where('code', $data['code'])
                ->where('deleted_at', 0);
            if (!empty($data['id'])) {
                $existingCity = $existingCity->where('id', '!=', $data['id']);
            }
            if ($existingCity->exists()) {
                throw new Exception('城市代码已存在');
            }

            // 判断是新建还是编辑
            if (!empty($data['id'])) {
                $city = CityModel::find($data['id']);
                if (!$city) {
                    throw new Exception('城市不存在');
                }
            } else {
                $city = new CityModel();
            }

            $city->name = $data['name'];
            $city->code = $data['code'];
            $city->image = $data['image'];
            $city->status = $data['status'] ?? 1;
            $city->updated_at = time();
            
            // 新建时设置创建时间
            if (empty($data['id'])) {
                $city->created_at = time();
            }
            
            if (!$city->save()) {
                throw new Exception(empty($data['id']) ? '添加失败' : '更新失败');
            }

            return json([
                'data' => $city,
                'msg' => empty($data['id']) ? '添加成功' : '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 软删除城市
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $city = CityModel::find($id);
            if (!$city) {
                throw new Exception('城市不存在');
            }

            // 软删除
            $city->deleted_at = time();
            if (!$city->save()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
} 